<!-- 过程检验单的添加修改组件 -->
<template>
  <div class="ipqc-form">
    <!-- 导航标签 -->
    <el-tabs v-model="activeTab" type="card" class="form-tabs">
      <el-tab-pane label="基本信息" name="basicInfo"></el-tab-pane>
      <el-tab-pane label="来源信息" name="sourceInfo"></el-tab-pane>
      <el-tab-pane label="检测数据" name="testData" v-if="type === 'edit'"></el-tab-pane>
      <el-tab-pane v-if="type === 'edit'" label="检测项目" name="testItems"></el-tab-pane>
    </el-tabs>

    <!-- 表单内容区域 -->
    <div class="form-content-area">
      <!-- 基本信息卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'basicInfo'">
        <div slot="header" class="card-header">
          <span>基本信息</span>
        </div>
        <el-form ref="form" :model="form" :rules="dynamicRules" label-width="100px" class="form-container">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检验单编号" prop="ipqcCode" class="form-item" required>
                <div class="code-input-wrapper">
                  <el-input
                    v-model="form.ipqcCode"
                    placeholder="请输入检验单编号"
                    :disabled="type === 'edit' || isSystemCode"
                    :class="{'disabled-input': type === 'edit'}" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="4" v-if="type !== 'edit'">
              <el-switch
                v-model="isSystemCode"
                active-text="系统编号"
                inactive-text=""
                style="margin-top: 13px;"
                @change="handleSystemCodeChange"
              ></el-switch>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检验单名称" prop="ipqcName" class="form-item" required>
                <el-input v-model="form.ipqcName" placeholder="请输入检验单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检测单类型" prop="ipqcType" class="form-item" required>
                <el-select v-model="form.ipqcType" placeholder="请选择检测单类型" style="width: 100%" @change="handleIpqcTypeChange" ref="ipqcTypeSelect">
                  <el-option
                    v-for="item in ipqcTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="质检方案" prop="inspectPlanId" class="form-item" required v-if="type === 'edit'">
                <div class="code-input-wrapper">
                  <el-input
                    v-model="form.inspectPlanId"
                    placeholder="请选择质检方案"
                    readonly />
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="small"
                    class="select-plan-btn"
                    @click="openInspectPlanDialog">选择</el-button>
                </div>
                <input type="hidden" v-model="form.inspectPlanCode" />
                <input type="hidden" v-model="form.inspectPlanName" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单据状态" prop="status" class="form-item" required>
                <el-select v-model="form.status" placeholder="请选择单据状态" style="width: 100%" disabled>
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <input type="hidden" v-model="form.status" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检测日期" prop="inspectDate" class="form-item" required>
                <el-date-picker
                  v-model="form.inspectDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择检测日期"
                  style="width: 100%">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 备注信息移到基本信息卡片 -->
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark" class="form-item">
                <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 产品信息卡片 - 在基本信息标签中显示 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'basicInfo'">
        <div slot="header" class="card-header">
          <span>产品信息</span>
        </div>
        <el-form ref="productForm" :model="form" label-width="100px" class="form-container">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="产品编码" prop="productCode" class="form-item" required>
                <el-input 
                  v-model="form.productCode" 
                  placeholder="请输入产品编码"
                  @input="handleProductCodeInput"
                  @blur="findTemplateByProductCode" />
                <input type="hidden" v-model="form.productId" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品名称" prop="productName" class="form-item" required>
                <el-input v-model="form.productName" placeholder="请输入产品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号" prop="productSfn" class="form-item" required>
                <el-input v-model="form.productSfn" placeholder="请输入规格型号" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 来源信息卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'sourceInfo'">
        <div slot="header" class="card-header">
          <span>来源信息</span>
        </div>
        <el-form ref="sourceForm" :model="form" label-width="100px" class="form-container">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="来源单据类型" prop="sourceDocType" class="form-item" required>
                <el-select
                  v-model="form.sourceDocType"
                  placeholder="请选择来源单据类型"
                  style="width: 100%"
                  :disabled="type === 'edit'"
                  :class="{'disabled-input': type === 'edit'}">
                  <el-option
                    v-for="item in sourceDocTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="来源单据编号" prop="sourceDocCode" class="form-item" required>
                <div class="code-input-wrapper">
                  <el-input v-model="form.sourceDocCode" placeholder="请输入来源单据编号" />
                  <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="small"
                    class="select-btn"
                    @click="openTaskDialog">
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="工单编码" prop="workOrderCode" class="form-item" required>
                <el-input v-model="form.workOrderCode" placeholder="请输入工单编码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工单名称" prop="workOrderName" class="form-item" required>
                <el-input v-model="form.workOrderName" placeholder="请输入工单名称" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="任务编号" prop="taskCode" class="form-item" required>
                <el-input v-model="form.taskCode" placeholder="请输入任务编号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="工序编码" prop="processCode" class="form-item">
                <el-input v-model="form.processCode" placeholder="请输入工序编码" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 检测结果卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'testData' && type === 'edit'">
        <div slot="header" class="card-header">
          <span>检测结果</span>
        </div>
        <el-form ref="testForm" :model="form" label-width="100px" class="form-container">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检测数量" prop="quantityCheckNum" class="form-item" required>
                <el-input-number v-model="form.quantityCheckNum" :min="0" :precision="0" style="width: 100%" @change="handleCheckNumChange" :disabled="type === 'edit'" />
                <div class="form-tip warning" v-if="form.receiveQuantity && form.quantityCheckNum > form.receiveQuantity">
                  <i class="el-icon-warning"></i> 检测数量不能超过接收数量({{ form.receiveQuantity }})
                </div>
                <div class="form-tip" v-if="form.minCheckNum">
                  <i class="el-icon-info"></i> 最低检测数: {{ form.minCheckNum }}
                </div>
                <div class="form-tip" v-if="type === 'edit'">
                  <i class="el-icon-info"></i> 编辑模式下检测数量不可修改
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="不合格数" prop="quantityUnqualifiedNum" class="form-item" required>
                <el-input-number v-model="form.quantityUnqualifiedNum" :min="0" :max="form.quantityCheckNum || 0" :precision="0" style="width: 100%" @change="handleUnqualifiedNumChange" />
                <div class="form-tip warning" v-if="form.maxUnqualifiedNum && form.quantityUnqualifiedNum > form.maxUnqualifiedNum">
                  <i class="el-icon-warning" style="color: #F56C6C;"></i> <strong>不合格数超过允许最大值({{ form.maxUnqualifiedNum }})，已自动设为不合格</strong>
                </div>
                <div class="form-tip" v-else-if="form.maxUnqualifiedNum">
                  <i class="el-icon-info"></i> 最大允许不合格数: {{ form.maxUnqualifiedNum }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="合格品数量" prop="quantityQualifiedNum" class="form-item" required>
                <el-input-number v-model="form.quantityQualifiedNum" :min="0" :max="form.quantityCheckNum || 0" :precision="0" style="width: 100%" :disabled="true" />
                <div class="form-tip">
                  <i class="el-icon-info"></i> 自动计算: 检测数量 - 不合格数 = 合格品数量
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="检测结果" prop="checkResult" class="form-item" required>
                <el-select v-model="form.checkResult" placeholder="请选择检测结果" style="width: 100%">
                  <el-option
                    v-for="item in checkResultOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="检测人员" prop="inspectorId" class="form-item" required>
                <el-input
                  v-model="form.inspectorName"
                  placeholder="请选择检测人员"
                  readonly
                  style="width: 80%; display: inline-block;"
                  @click="openUserDialog"
                />
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  @click="openUserDialog"
                  style="margin-left: 8px;"
                >选择</el-button>
                <!-- 使用隐藏字段保存inspectorId -->
                <input type="hidden" v-model="form.inspectorId" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 缺陷率详细信息 -->
          <div class="defect-details-section">
            <div class="section-divider">缺陷率详细信息</div>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="致命缺陷率" prop="crRate" class="form-item" required>
                  <el-input-number v-model="form.crRate" :min="0" :precision="2" :step="0.01" style="width: 100%" :disabled="true" />
                  <div class="form-tip" v-if="form.crQuantityNum > 0">
                    <i class="el-icon-info"></i> 致命缺陷率：{{ form.crRate }}% (自动计算)
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="严重缺陷率" prop="majRate" class="form-item" required>
                  <el-input-number v-model="form.majRate" :min="0" :precision="2" :step="0.01" style="width: 100%" :disabled="true" />
                  <div class="form-tip" v-if="form.majQuantityNum > 0">
                    <i class="el-icon-info"></i> 严重缺陷率：{{ form.majRate }}% (自动计算)
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="轻微缺陷率" prop="minRate" class="form-item" required>
                  <el-input-number v-model="form.minRate" :min="0" :precision="2" :step="0.01" style="width: 100%" :disabled="true" />
                  <div class="form-tip" v-if="form.minQuantityNum > 0">
                    <i class="el-icon-info"></i> 轻微缺陷率：{{ form.minRate }}% (自动计算)
                  </div>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="致命缺陷数量" prop="crQuantityNum" class="form-item" required>
                  <el-input-number v-model="form.crQuantityNum" :min="0" :precision="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="严重缺陷数量" prop="majQuantityNum" class="form-item" required>
                  <el-input-number v-model="form.majQuantityNum" :min="0" :precision="0" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="轻微缺陷数量" prop="minQuantityNum" class="form-item" required>
                  <el-input-number v-model="form.minQuantityNum" :min="0" :precision="0" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-card>

      <!-- 检测项目卡片 -->
      <el-card class="form-card" shadow="hover" v-show="activeTab === 'testItems' && type === 'edit'">
        <div slot="header" class="card-header">
          <span>检测项目列表</span>
          <div class="header-right">
            <el-button type="text" icon="el-icon-refresh" @click="refreshTestItems">刷新</el-button>
          </div>
        </div>
        <!-- 使用新的检测项目列表组件 -->
        <test-items-list
          ref="testItemsListRef"
          :ipqcId="form.ipqcId"
          :templateId="form.inspectPlanId"
          @edit="handleEditTestItem"
          @view="handleViewTestItem"
        />
      </el-card>
    </div>

    <!-- 底部按钮区域 -->
    <div class="form-footer">
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      <el-button @click="cancel" :disabled="submitLoading">取 消</el-button>
    </div>

    <!-- 任务选择对话框 -->
    <el-dialog
      title="选择任务"
      :visible.sync="taskDialogVisible"
      width="900px"
      append-to-body
      :destroy-on-close="true">
      <div class="task-dialog-container">
        <!-- 搜索区域 -->
        <el-form :inline="true" :model="taskQueryParams" class="search-form">
          <el-form-item label="工单编码">
            <el-input
              v-model="taskQueryParams.workOrderCode"
              placeholder="请输入工单编码"
              clearable
              size="small"
              @keyup.enter.native="handleTaskSearch"
            />
          </el-form-item>
          <el-form-item label="工单名称">
            <el-input
              v-model="taskQueryParams.workOrderName"
              placeholder="请输入工单名称"
              clearable
              size="small"
              @keyup.enter.native="handleTaskSearch"
            />
          </el-form-item>
          <el-form-item label="任务编号">
            <el-input
              v-model="taskQueryParams.taskCode"
              placeholder="请输入任务编号"
              clearable
              size="small"
              @keyup.enter.native="handleTaskSearch"
            />
          </el-form-item>
          <el-form-item label="任务名称">
            <el-input
              v-model="taskQueryParams.taskName"
              placeholder="请输入任务名称"
              clearable
              size="small"
              @keyup.enter.native="handleTaskSearch"
            />
          </el-form-item>
          <el-form-item label="工序编码">
            <el-input
              v-model="taskQueryParams.processCode"
              placeholder="请输入工序编码"
              clearable
              size="small"
              @keyup.enter.native="handleTaskSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="handleTaskSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" size="small" @click="resetTaskSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 表格区域 -->
        <el-table
          v-loading="taskListLoading"
          :data="taskList"
          @row-click="selectTask"
          style="width: 100%">
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column prop="taskCode" label="任务编号" :show-overflow-tooltip="true" />
          <el-table-column prop="taskName" label="任务名称" :show-overflow-tooltip="true" />
          <el-table-column prop="workOrderCode" label="工单编码" :show-overflow-tooltip="true" />
          <el-table-column prop="workOrderName" label="工单名称" :show-overflow-tooltip="true" />
          <el-table-column prop="processCode" label="工序编码" :show-overflow-tooltip="true" />
          <el-table-column prop="planQuantity" label="计划数量" :show-overflow-tooltip="true" width="100" />
          <el-table-column label="状态" width="100" align="center">
            <template slot-scope="scope">
              <el-tag :type="getTaskStatusType(scope.row.status)">{{ getTaskStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click.stop="selectTask(scope.row)"
              >选择</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加分页组件 -->
        <pagination
          v-show="taskTotal > 0"
          :total="taskTotal"
          :page.sync="taskQueryParams.pageNum"
          :limit.sync="taskQueryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </el-dialog>

    <!-- 员工选择弹窗 -->
    <select-user-dialog
      :visible.sync="userDialogVisible"
      title="选择检测人员"
      :multi="false"
      @confirm="handleUserConfirm"
    />
  </div>
</template>

<script>
import axios from 'axios';
import { getAutoNumbers, getAutoNumbersConsume } from "@/api/basic/numbers.js";
import { getQcTemplateProductList } from "@/api/qc/IncomingInspection";
import { getTaskListForQc, selectQcIpqcProductInfo } from "@/api/qc/ProcesInspection";
import { selectQcTemplateProductProductCode, selectQcTemplateProductMaterialCode } from "@/api/qc/QualitySchemeOrder";
import TestItemsList from "./TestItemsList";
import SelectUserDialog from '@/views/sc/task/SelectUserDialog.vue';
import Pagination from "@/components/Pagination";

export default {
  name: "IpqcForm",
  components: {
    TestItemsList,
    SelectUserDialog,
    Pagination
  },
  props: {
    // 表单数据
    formData: {
      type: Object,
      default: () => ({})
    },
    // 操作类型（新增/修改）
    type: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      // 当前激活的标签
      activeTab: 'basicInfo',
      // 表单提交加载状态
      submitLoading: false,
      // 系统编号开关状态
      isSystemCode: true,
      // 表单参数
      form: {
        ipqcId: null,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: '3', // 默认为过程检验
        inspectPlanId: null,      // 质检方案ID
        inspectPlanCode: null,    // 质检方案编码
        inspectPlanName: null,    // 质检方案名称
        sourceDocType: '3', // 默认为过程检验单
        sourceDocCode: null,
        sourceDocId: null,        // 来源单据ID
        sourceLineId: null,       // 来源行ID
        workOrderId: null,        // 工单ID
        workOrderCode: null,
        workOrderName: null,
        taskId: null,             // 任务ID
        taskCode: null,
        factoryId: null,          // 工厂ID
        factoryCode: null,
        factoryName: null,
        processId: null,          // 工序ID
        processCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSfn: null,
        unit: null,
        receiveQuantity: 0,       // 接收数量
        minCheckNum: 0,           // 最低检测数
        maxUnqualifiedNum: 0,     // 最大不合格数
        quantityCheckNum: 0,
        quantityUnqualifiedNum: 0,
        quantityQualifiedNum: 0,
        // 添加缺陷率相关字段
        crRate: 0,
        majRate: 0,
        minRate: 0,
        crQuantityNum: 0,
        majQuantityNum: 0,
        minQuantityNum: 0,
        checkResult: null,
        status: '1',
        inspectDate: new Date().toISOString().split('T')[0],
        remark: null,
        inspectorId: null, // 添加检测人员字段
        inspectorName: '' // 添加检测人员名称
      },
      // 已移除 autoCodeLoading，改用 isSystemCode 控制系统编号功能

      // 任务选择对话框
      taskDialogVisible: false,
      // 任务列表数据
      taskList: [],
      // 任务列表加载状态
      taskListLoading: false,
      // 任务列表查询参数
      taskQueryParams: {
        workOrderCode: '',
        workOrderName: '',
        processCode: '',
        taskName: '',
        taskCode: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      },
      // 任务总数
      taskTotal: 0,
      // 存储所有任务数据（用于前端分页）
      allTaskList: [],
      // 是否使用本地分页
      useLocalPagination: true,

      // 选项数据
      ipqcTypeOptions: [
        { value: '1', label: '首检' },
        { value: '2', label: '巡检' },
        { value: '3', label: '报工质检' }
      ],
      sourceDocTypeOptions: [
        { value: '1', label: '生产任务单' },
        { value: '2', label: '来料货检验单' },
        { value: '3', label: '过程检验单' },
        { value: '4', label: '退料检验单' }
      ],
      checkResultOptions: [
        { value: '1', label: '合格' },
        { value: '2', label: '不合格' },
        { value: '3', label: '待检' }
      ],
      statusOptions: [
        { value: '1', label: '草稿' },
        { value: '2', label: '已提交' },
        { value: '3', label: '已审核' }
      ],
      userDialogVisible: false
    }
  },
  computed: {
    // 动态表单验证规则
    dynamicRules() {
      const baseRules = {
        ipqcCode: [
          { required: true, message: "请输入检验单编号", trigger: "blur" }
        ],
        ipqcName: [
          { required: true, message: "请输入检验单名称", trigger: "blur" }
        ],
        ipqcType: [
          { required: true, message: "请选择检测单类型", trigger: "change" }
        ],
        inspectPlanId: [
          { required: true, message: "请选择质检方案", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择单据状态", trigger: "change" }
        ],
        inspectDate: [
          { required: true, message: "请选择检测日期", trigger: "change" }
        ],
        quantityCheckNum: [
          { required: true, message: "请输入检测数量", trigger: "blur" }
        ],
        quantityUnqualifiedNum: [
          { required: true, message: "请输入不合格数", trigger: "blur" }
        ],
        quantityQualifiedNum: [
          { required: true, message: "请输入合格品数量", trigger: "blur" }
        ],
        checkResult: [
          { required: true, message: "请选择检测结果", trigger: "change" }
        ],
        inspectorId: [
          { required: true, message: "请选择检测人员", trigger: "change" },
          { type: "string", message: "检测人员格式不正确", trigger: "change" }
        ],
        crRate: [
          { required: true, message: "请输入致命缺陷率", trigger: "blur" }
        ],
        majRate: [
          { required: true, message: "请输入严重缺陷率", trigger: "blur" }
        ],
        minRate: [
          { required: true, message: "请输入轻微缺陷率", trigger: "blur" }
        ],
        crQuantityNum: [
          { required: true, message: "请输入致命缺陷数量", trigger: "blur" }
        ],
        majQuantityNum: [
          { required: true, message: "请输入严重缺陷数量", trigger: "blur" }
        ],
        minQuantityNum: [
          { required: true, message: "请输入轻微缺陷数量", trigger: "blur" }
        ],
        // 添加产品相关字段验证规则
        productCode: [
          { required: true, message: "请输入产品编码", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "请输入产品名称", trigger: "blur" }
        ],
        productSfn: [
          { required: true, message: "请输入规格型号", trigger: "blur" }
        ]
      };

      // 新增模式下，其他字段可选
      if (this.type === 'add') {
        baseRules.sourceDocType = [
          { required: false, message: "请选择来源单据类型", trigger: "change" }
        ];
        baseRules.workOrderCode = [
          { required: false, message: "请输入工单编码", trigger: "blur" }
        ];
        baseRules.workOrderName = [
          { required: false, message: "请输入工单名称", trigger: "blur" }
        ];
        baseRules.taskCode = [
          { required: false, message: "请输入任务编号", trigger: "blur" }
        ];
        baseRules.factoryCode = [
          { required: false, message: "请输入工厂编号", trigger: "blur" }
        ];
        baseRules.factoryName = [
          { required: false, message: "请输入工厂名称", trigger: "blur" }
        ];
        baseRules.processCode = [
          { required: false, message: "请输入工序编码", trigger: "blur" }
        ];
      } else {
        // 编辑模式下，所有字段都必填
        baseRules.sourceDocType = [
          { required: true, message: "请选择来源单据类型", trigger: "change" }
        ];
        baseRules.sourceDocCode = [
          { required: true, message: "请输入来源单据编号", trigger: "blur" }
        ];
        baseRules.workOrderCode = [
          { required: true, message: "请输入工单编码", trigger: "blur" }
        ];
        baseRules.workOrderName = [
          { required: true, message: "请输入工单名称", trigger: "blur" }
        ];
        baseRules.taskCode = [
          { required: true, message: "请输入任务编号", trigger: "blur" }
        ];
        baseRules.factoryCode = [
          { required: true, message: "请输入工厂编号", trigger: "blur" }
        ];
        baseRules.factoryName = [
          { required: true, message: "请输入工厂名称", trigger: "blur" }
        ];
        baseRules.processCode = [
          { required: true, message: "请输入工序编码", trigger: "blur" }
        ];
      }

      return baseRules;
    }
  },
  watch: {
    // 监听表单数据变化
    formData: {
      handler(val) {
        // 清除验证信息，确保表单数据变化时不显示错误提示
        this.clearValidateMessages();
        
        if (val && Object.keys(val).length > 0) {
          // 调试日志 - 显示原始数据
          console.log('【调试】formData原始数据:', JSON.stringify(val));
          console.log('【调试】检测人员字段:', {
            inspectorId: val.inspectorId,
            inspectorName: val.inspectorName,
            userId: val.userId,
            userName: val.userName,
            nickName: val.nickName,
            inspector: val.inspector  // 添加对inspector字段的检查
          });

          // 处理编辑模式下可能存在的方案ID问题
          let formDataCopy = { ...val };

          // 处理检测人员字段显示问题
          console.log('编辑模式 - 处理前的检测人员数据:', {
            inspectorId: formDataCopy.inspectorId,
            inspectorName: formDataCopy.inspectorName,
            inspector: formDataCopy.inspector
          });

          // 如果有inspector字段（后端数据库字段名），则优先使用它
          if (formDataCopy.inspector) {
            console.log('发现inspector字段，值为:', formDataCopy.inspector);
            formDataCopy.inspectorName = formDataCopy.inspector;
            formDataCopy.inspectorId = formDataCopy.inspector;
            console.log('已将inspector的值设置到inspectorName和inspectorId:', formDataCopy.inspectorName);
          }
          // 如果inspectorId存在但inspectorName不存在，则将inspectorId的值复制给inspectorName
          else if (formDataCopy.inspectorId && !formDataCopy.inspectorName) {
            formDataCopy.inspectorName = formDataCopy.inspectorId;
            console.log('已将inspectorId的值复制给inspectorName:', formDataCopy.inspectorName);
          }
          
          // 如果有userId/userName/nickName字段但没有inspectorId/inspectorName，则使用这些值
          if (!formDataCopy.inspectorId && !formDataCopy.inspectorName) {
            if (formDataCopy.userId || formDataCopy.userName || formDataCopy.nickName) {
              console.log('使用userId/userName/nickName字段填充检测人员信息');
              // 优先使用nickName，其次是userName
              formDataCopy.inspectorName = formDataCopy.nickName || formDataCopy.userName || String(formDataCopy.userId || '');
              formDataCopy.inspectorId = formDataCopy.inspectorName;
              console.log('填充后的检测人员信息:', {
                inspectorId: formDataCopy.inspectorId,
                inspectorName: formDataCopy.inspectorName
              });
            }
          }

          // 重要：后端返回的是templateId而不是inspectPlanId，需要映射
          if (!formDataCopy.inspectPlanId && formDataCopy.templateId) {
            console.log('【调试】发现templateId，映射到inspectPlanId:', formDataCopy.templateId);
            formDataCopy.inspectPlanId = formDataCopy.templateId;
          }

          // 如果有质检方案ID，确保它是数值类型
          if (formDataCopy.inspectPlanId) {
            // 转换inspectPlanId为数值类型
            let planId = formDataCopy.inspectPlanId;
            console.log('【调试】处理前planId类型:', typeof planId);
            console.log('【调试】处理前planId值:', planId);
            console.log('【调试】是否为对象:', typeof planId === 'object' && planId !== null);

            if (typeof planId === 'object' && planId !== null) {
              console.warn('加载数据时发现方案ID是对象类型，尝试获取其数值表示', planId);
              // 如果是对象，尝试提取其中的ID值
              console.log('【调试】对象属性:', Object.keys(planId));

              if (planId.id !== undefined) {
                console.log('【调试】使用planId.id:', planId.id);
                planId = planId.id;
              } else if (planId.planId !== undefined) {
                console.log('【调试】使用planId.planId:', planId.planId);
                planId = planId.planId;
              } else {
                console.error('无法从对象中提取有效ID', planId);
                this.$message.error('方案ID格式不正确');
                return;
              }
            }

            // 转换为数值
            const originalPlanId = planId;
            planId = parseInt(planId, 10);
            console.log('【调试】parseInt前:', originalPlanId, '类型:', typeof originalPlanId);
            console.log('【调试】parseInt后:', planId, '类型:', typeof planId);

            if (isNaN(planId)) {
              console.error('方案ID不是有效数字:', formDataCopy.inspectPlanId);
              this.$message.error('方案ID必须是数字');
              return;
            }

            // 更新为数值类型
            formDataCopy.inspectPlanId = planId;

            // 确保我们保留方案名称作为隐藏字段，但输入框只显示ID
            if (formDataCopy.inspectPlanName && formDataCopy.inspectPlanName.includes('[ID:')) {
              formDataCopy.inspectPlanName = formDataCopy.inspectPlanName.split('[ID:')[0].trim();
            }

            console.log('【调试】编辑模式 - 最终方案ID:', planId, '类型:', typeof planId);
            console.log('【调试】方案名称:', formDataCopy.inspectPlanName);
          } else {
            console.log('【调试】没有找到inspectPlanId值');
          }

          // 使用处理后的数据更新表单
          this.form = { ...this.form, ...formDataCopy };
          console.log('【调试】更新后的表单inspectPlanId:', this.form.inspectPlanId, '类型:', typeof this.form.inspectPlanId);
          
          // 在编辑模式下，如果有产品ID，自动查询质检方案
          if (this.type === 'edit' && this.form.productId) {
            this.$nextTick(() => {
              this.findTemplateByProductCode();
            });
          }
          
          // 计算缺陷率
          this.$nextTick(() => {
            this.calculateDefectRates();
            this.updateQualifiedQuantity();
          });
        }
      },
      immediate: true,
      deep: true
    },
    // 监听缺陷数量变化，自动计算缺陷率
    'form.crQuantityNum': function(val) {
      this.calculateDefectRates();
    },
    'form.majQuantityNum': function(val) {
      this.calculateDefectRates();
    },
    'form.minQuantityNum': function(val) {
      this.calculateDefectRates();
    },
    'activeTab': {
      handler(val) {
        if (val === 'testItems' && this.$refs.testItemsListRef && this.type === 'edit') {
          // 当切换到检测项目标签时，刷新数据
          this.$nextTick(() => {
            this.refreshTestItems();
          });
        }
      }
    },
    // 监听组件类型变化，在模式切换时清除验证信息
    type: {
      handler(newType) {
        console.log('组件类型变化:', newType);
        // 清除验证信息
        this.clearValidateMessages();
      },
      immediate: true
    }
  },
  mounted() {
    console.log('【调试-mounted】组件挂载，检查inspectPlanId和templateId');
    console.log('【调试-mounted】当前form.inspectPlanId:', this.form.inspectPlanId);
    console.log('【调试-mounted】当前form.templateId:', this.form.templateId);
    console.log('【调试-mounted】当前检测人员信息:', {
      inspectorId: this.form.inspectorId,
      inspectorName: this.form.inspectorName,
      inspector: this.form.inspector
    });
    
    // 进入组件时清空所有表单验证提示
    this.clearValidateMessages();

    // 检查检测人员字段
    if (this.form.inspector) {
      console.log('【调试-mounted】发现inspector字段，值为:', this.form.inspector);
      this.form.inspectorName = this.form.inspector;
      this.form.inspectorId = this.form.inspector;
    }
    else if (this.form.inspectorId && !this.form.inspectorName) {
      console.log('【调试-mounted】发现inspectorId但无inspectorName，复制值');
      this.form.inspectorName = this.form.inspectorId;
    }

    // 重要：后端返回的是templateId而不是inspectPlanId，需要映射
    if (!this.form.inspectPlanId && this.form.templateId) {
      console.log('【调试-mounted】发现templateId，映射到inspectPlanId:', this.form.templateId);
      this.form.inspectPlanId = this.form.templateId;
    }

    // 组件挂载后，如果有inspectPlanId，处理数据
    if (this.form.inspectPlanId) {
      console.log('【调试-mounted】发现inspectPlanId:', this.form.inspectPlanId, '类型:', typeof this.form.inspectPlanId);

      // 确保inspectPlanId是数值类型
      let planId = this.form.inspectPlanId;
      if (typeof planId === 'object' && planId !== null) {
        console.warn('【调试-mounted】挂载时发现方案ID是对象类型，尝试获取其数值表示', JSON.stringify(planId));
        console.log('【调试-mounted】对象属性:', Object.keys(planId));
        // 这种情况在watch中已处理
      } else {
        // 转换为数值
        const originalPlanId = planId;
        planId = parseInt(planId, 10);
        console.log('【调试-mounted】parseInt前:', originalPlanId, '类型:', typeof originalPlanId);
        console.log('【调试-mounted】parseInt后:', planId, '类型:', typeof planId);

        if (!isNaN(planId)) {
          this.form.inspectPlanId = planId; // 更新为数值类型
          console.log('【调试-mounted】更新后的inspectPlanId:', this.form.inspectPlanId);
        } else {
          console.error('【调试-mounted】无法转换为数值:', originalPlanId);
        }
      }

      // 保留方案名称作为隐藏字段，移除ID后缀如果存在
      if (this.form.inspectPlanName && this.form.inspectPlanName.includes('[ID:')) {
        const originalName = this.form.inspectPlanName;
        this.form.inspectPlanName = this.form.inspectPlanName.split('[ID:')[0].trim();
        console.log('【调试-mounted】处理方案名称 - 原始:', originalName, '处理后:', this.form.inspectPlanName);
      }

      // 如果当前是在检测项目标签，刷新检测项目列表
      if (this.activeTab === 'testItems' && this.$refs.testItemsListRef && this.type === 'edit') {
        this.$nextTick(() => {
          this.refreshTestItems();
        });
      }
    } else {
      console.log('【调试-mounted】没有找到inspectPlanId值');
    }
  },
  created() {
    // 如果是新增模式且启用了系统编号，则生成编号
    if (this.type !== 'edit' && this.isSystemCode) {
      this.generatePlanCode();
      this.form.status = '2';
    }
     // 如果是编辑模式，默认选择“已审核”状态
    if (this.type === 'edit') {
      this.form.status = '3';
    }
  },
  methods: {
    // 表单提交
    submitForm() {
      console.log('【调试】开始提交表单');
      console.log('【调试】当前表单数据:', this.form);
      console.log('【调试】当前操作类型:', this.type);

      this.$refs.form.validate(async valid => {
        console.log('【调试】表单验证结果:', valid);
        if (valid) {
          console.log('【调试】表单验证通过，准备提交数据');
          
          // 设置加载状态
          this.submitLoading = true;
          
          // 显示全屏加载
          const loadingInstance = this.$loading({
            lock: true,
            text: this.type === 'add' ? '正在保存数据...' : '正在更新数据...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });

          // 如果启用了系统编号且不是编辑模式，在提交前获取最终编号
          if (this.isSystemCode && this.type !== 'edit') {
            try {
              const response = await getAutoNumbersConsume(8);
              if (response && response.code === 200) {
                this.form.ipqcCode = response.msg;
              } else {
                this.$message.error('获取最终编号失败，请重试');
                this.submitLoading = false;
                loadingInstance.close();
                return;
              }
            } catch (error) {
              this.$message.error('获取最终编号失败，请重试');
              this.submitLoading = false;
              loadingInstance.close();
              return;
            }
          }

          // 创建提交数据，进行字段映射
          const submitData = { ...this.form };

          // 确保inspectorId是字符串类型
          if (submitData.inspectorId) {
            submitData.inspectorId = String(submitData.inspectorId);
          }
          
          // 将inspectorId/inspectorName的值设置回inspector字段
          submitData.inspector = submitData.inspectorName || submitData.inspectorId || '';
          console.log('【调试】设置inspector字段:', submitData.inspector);

          // 重要：将inspectPlanId映射为templateId，因为后端数据库字段是template_id
          if (submitData.inspectPlanId) {
            submitData.templateId = submitData.inspectPlanId;
            console.log('【调试】字段映射 - inspectPlanId -> templateId:', submitData.templateId);
          }

          // 确保其他必要字段存在
          if (!submitData.sourceDocType) {
            submitData.sourceDocType = '3'; // 默认为过程检验单
          }

          // 设置缺失的ID字段默认值
          if (!submitData.workOrderId) {
            submitData.workOrderId = 0; // 默认为0，表示无关联工单
          }
          if (!submitData.taskId) {
            submitData.taskId = 0; // 默认为0，表示无关联任务
          }
          if (!submitData.factoryId) {
            submitData.factoryId = 0; // 默认为0，表示无关联工厂
          }
          if (!submitData.processId) {
            submitData.processId = 0; // 默认为0，表示无关联工序
          }
          if (!submitData.sourceDocId) {
            submitData.sourceDocId = 0; // 默认为0，表示无关联来源单据
          }
          if (!submitData.sourceLineId) {
            submitData.sourceLineId = 0; // 默认为0，表示无关联来源行
          }

          console.log('【调试】最终提交数据:', submitData);
          
          // 发送提交事件，并在父组件处理完成后关闭加载状态
          this.$emit('submit', submitData, () => {
            // 关闭加载状态
            this.submitLoading = false;
          });
        } else {
          console.log('【调试】表单验证失败，请检查必填字段');
          // 显示具体的验证错误信息
          this.$message.error('请完善必填信息后再提交');

          // 显示具体的验证错误
          this.$nextTick(() => {
            const errorFields = [];
            if (!this.form.ipqcCode) errorFields.push('检验单编号');
            if (!this.form.ipqcName) errorFields.push('检验单名称');
            if (!this.form.ipqcType) errorFields.push('检测单类型');
            if (!this.form.inspectPlanId) errorFields.push('质检方案');
            if (!this.form.status) errorFields.push('单据状态');
            if (!this.form.inspectDate) errorFields.push('检测日期');
            if (!this.form.quantityCheckNum) errorFields.push('检测数量');
            if (!this.form.quantityUnqualifiedNum) errorFields.push('不合格数');
            if (!this.form.quantityQualifiedNum) errorFields.push('合格品数量');
            if (!this.form.checkResult) errorFields.push('检测结果');
            if (!this.form.inspectorId) errorFields.push('检测人员');
            if (!this.form.crRate) errorFields.push('致命缺陷率');
            if (!this.form.majRate) errorFields.push('严重缺陷率');
            if (!this.form.minRate) errorFields.push('轻微缺陷率');
            if (!this.form.crQuantityNum) errorFields.push('致命缺陷数量');
            if (!this.form.majQuantityNum) errorFields.push('严重缺陷数量');
            if (!this.form.minQuantityNum) errorFields.push('轻微缺陷数量');

            if (errorFields.length > 0) {
              this.$message.warning(`请填写以下必填字段：${errorFields.join('、')}`);
            }
          });
        }
      });
    },
    // 取消
    cancel() {
      this.resetForm();
      this.$emit('cancel');
    },
    // 清除表单验证信息
    clearValidateMessages() {
      // 使用nextTick确保DOM更新后再清除验证信息
      this.$nextTick(() => {
        // 清除主表单验证
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
        
        // 清除产品信息表单验证
        if (this.$refs.productForm) {
          this.$refs.productForm.clearValidate();
        }
        
        // 清除来源信息表单验证
        if (this.$refs.sourceForm) {
          this.$refs.sourceForm.clearValidate();
        }
        
        // 清除检测结果表单验证
        if (this.$refs.testForm) {
          this.$refs.testForm.clearValidate();
        }
      });
    },
    
    // 重置表单
    resetForm() {
      // 重置所有表单字段
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
      if (this.$refs.productForm) {
        this.$refs.productForm.resetFields();
      }
      if (this.$refs.sourceForm) {
        this.$refs.sourceForm.resetFields();
      }
      if (this.$refs.testForm) {
        this.$refs.testForm.resetFields();
      }
      
      // 清除所有表单验证提示
      this.clearValidateMessages();
      this.form = {
        ipqcId: null,
        ipqcCode: null,
        ipqcName: null,
        ipqcType: '3', // 默认为过程检验
        inspectPlanId: null,      // 质检方案ID
        inspectPlanCode: null,    // 质检方案编码
        inspectPlanName: null,    // 质检方案名称
        sourceDocType: '3', // 默认为过程检验单
        sourceDocCode: null,
        sourceDocId: null,        // 来源单据ID
        sourceLineId: null,       // 来源行ID
        workOrderId: null,        // 工单ID
        workOrderCode: null,
        workOrderName: null,
        taskId: null,             // 任务ID
        taskCode: null,
        factoryId: null,          // 工厂ID
        factoryCode: null,
        factoryName: null,
        processId: null,          // 工序ID
        processCode: null,
        productId: null,
        productCode: null,
        productName: null,
        productSfn: null,
        unit: null,
        receiveQuantity: 0,       // 接收数量
        minCheckNum: 0,           // 最低检测数
        maxUnqualifiedNum: 0,     // 最大不合格数
        quantityCheckNum: 0,
        quantityUnqualifiedNum: 0,
        quantityQualifiedNum: 0,
        // 添加缺陷率相关字段
        crRate: 0,
        majRate: 0,
        minRate: 0,
        crQuantityNum: 0,
        majQuantityNum: 0,
        minQuantityNum: 0,
        checkResult: null,
        status: '1',
        inspectDate: new Date().toISOString().split('T')[0],
        remark: null,
        inspectorId: null, // 添加检测人员字段
        inspectorName: '' // 添加检测人员名称
      };
    },

    // 验证表单并提交
    validateForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 设置加载状态
          this.submitLoading = true;
          
          // 显示全屏加载
          const loadingInstance = this.$loading({
            lock: true,
            text: this.type === 'add' ? '正在保存数据...' : '正在更新数据...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          
          // 发送提交事件，并在父组件处理完成后关闭加载状态
          this.$emit('submit', this.form, () => {
            // 关闭加载状态
            this.submitLoading = false;
          });
        }
      });
    },

    // 打开质检方案选择对话框
    openInspectPlanDialog() {
      // 检查是否已有检测方案ID
      if (this.form.inspectPlanId) {
        this.$confirm('当前已选择检测方案，是否重新选择?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户确认重新选择
          this.$emit('openInspectPlanDialog');
        }).catch(() => {
          // 用户取消重新选择
          this.$message.info('已取消重新选择');
        });
      } else {
        // 直接打开选择对话框
        this.$emit('openInspectPlanDialog');
      }
    },

    // 选择质检方案后的回调
    selectInspectPlan(plan) {
      if (plan) {
        // 确保planId是数值类型
        let planId = plan.planId;
        if (typeof planId === 'object' && planId !== null) {
          console.warn('方案ID是对象类型，尝试获取其数值表示', planId);
          // 如果是对象，尝试提取其中的ID值
          if (planId.id !== undefined) {
            planId = planId.id;
          } else if (planId.planId !== undefined) {
            planId = planId.planId;
          } else {
            console.error('无法从对象中提取有效ID', planId);
            this.$message.error('方案ID格式不正确');
            return;
          }
        }

        // 转换为数值
        planId = parseInt(planId, 10);
        if (isNaN(planId)) {
          this.$message.error('方案ID必须是数字');
          return;
        }

        // 设置基本字段 - 只更新ID和隐藏字段
        this.form.inspectPlanId = planId; // 使用处理后的数值，也是显示在输入框中的值
        this.form.inspectPlanCode = plan.planCode;
        this.form.inspectPlanName = plan.planName; // 仍然保存名称，但作为隐藏字段

        // 显示简单成功消息
        this.$message.success(`已选择方案，ID: ${planId}`);

        // 如果有原始数据，可以获取更多信息
        if (plan.originalData) {
          console.log('质检方案原始数据:', plan.originalData);
        }

        // 触发表单验证
        this.$nextTick(() => {
          this.$refs.form.validateField('inspectPlanId'); // 验证ID字段

          // 如果当前是在检测项目标签，刷新检测项目列表
          if (this.activeTab === 'testItems' && this.$refs.testItemsListRef && this.type === 'edit') {
            this.refreshTestItems();
          }
        });
      }
    },

    // 原有的generateAutoCode方法已被generatePlanCode方法替代

    // 刷新检测项目列表
    refreshTestItems() {
      if (this.$refs.testItemsListRef) {
        console.log('刷新检测项目列表');
        this.$refs.testItemsListRef.refresh();
      }
    },

    // 编辑检测项目
    handleEditTestItem(row) {
      this.$message.info('暂未实现编辑检测项功能');
      console.log('编辑检测项:', row);
    },

    // 查看检测项目
    handleViewTestItem(row) {
      this.$message.info('暂未实现查看检测项详情功能');
      console.log('查看检测项:', row);
    },

    // 处理检测单类型变更
    handleIpqcTypeChange(value) {
      // 自动设置来源单据查询条件的状态
      if (value === '1' || value === '2') {
        this.taskQueryParams.status = '2';
      } else if (value === '3') {
        this.taskQueryParams.status = '3';
      }
    },
    openTaskDialog() {
      // 检查是否已选择检测单类型
      if (!this.form.ipqcType) {
        this.$message.warning('请先选择检测单类型');
        // 切换到基本信息标签页
        this.activeTab = 'basicInfo';
        // 等待DOM更新后聚焦到检测单类型选择框
        this.$nextTick(() => {
          // 尝试聚焦到检测单类型选择框
          if (this.$refs.ipqcTypeSelect) {
            this.$refs.ipqcTypeSelect.focus();
          }
        });
        return;
      }
      
      // 根据当前检测单类型设置查询状态（如果已选择）
      if (this.form.ipqcType) {
        if (this.form.ipqcType === '1' || this.form.ipqcType === '2') {
          this.taskQueryParams.status = '2';
        } else if (this.form.ipqcType === '3') {
          this.taskQueryParams.status = '3';
        }
      } else {
        // 默认不设置状态限制
        this.taskQueryParams.status = '';
      }
      
      // 直接打开任务选择对话框
      this.taskDialogVisible = true;
      this.fetchTaskList();
    },
    // 获取任务列表
    async fetchTaskList() {
      this.taskListLoading = true;

      // 打印调试信息
      console.log('开始获取任务列表，查询参数:', this.taskQueryParams);

      try {
        // 构建查询参数 - 如果使用本地分页，不发送分页参数
        const params = {
          workOrderCode: this.taskQueryParams.workOrderCode || '',
          workOrderName: this.taskQueryParams.workOrderName || '',
          processCode: this.taskQueryParams.processCode || '',
          taskName: this.taskQueryParams.taskName || '',
          taskCode: this.taskQueryParams.taskCode || '',
          status: this.taskQueryParams.status || ''
        };
        
        // 只有不使用本地分页时才发送分页参数
        if (!this.useLocalPagination) {
          params.pageNum = this.taskQueryParams.pageNum;
          params.pageSize = this.taskQueryParams.pageSize;
        }

        // 通过axios发送请求
        const response = await axios({
          url: process.env.VUE_APP_BASE_API + '/ldzl-qc/ipqc/qc-query/all-tasks',
          method: 'get',
          headers: {
            'Authorization': 'Bearer ' + this.$store.getters.token,
            'from-source': 'ldzl-qc', // 根据后端接口要求设置来源
            'Content-Type': 'application/json;charset=UTF-8'
          },
          params: params,
          withCredentials: true
        });

        console.log('任务列表响应数据:', response);

        // 处理响应数据
        if (response && response.data) {
          if (response.data.code === 200) {
            // 成功响应
            let rawData = [];
            if (Array.isArray(response.data.data)) {
              rawData = response.data.data;
              this.taskTotal = response.data.total || rawData.length;
            } else if (response.data.rows && Array.isArray(response.data.rows)) {
              // 兼容不同的返回格式
              rawData = response.data.rows;
              this.taskTotal = response.data.total || rawData.length;
            } else {
              rawData = [];
              this.taskTotal = 0;
              console.warn('响应数据格式不符合预期:', response.data);
            }
            
            // 存储全部数据
            this.allTaskList = rawData;
            
            // 如果使用本地分页，计算当前页的数据
            if (this.useLocalPagination) {
              this.updateLocalPagination();
            } else {
              // 不使用本地分页，直接使用返回的数据
              this.taskList = rawData;
            }
          } else {
            // 请求成功但业务失败
            this.$message.error(response.data.msg || '获取任务列表失败');
            this.taskList = [];
            this.allTaskList = [];
            this.taskTotal = 0;
          }
        } else {
          this.taskList = [];
          this.allTaskList = [];
          this.taskTotal = 0;
          console.log('任务列表为空');
        }
      } catch (error) {
        console.error('获取任务列表异常:', error);

        if (error.response) {
          // 服务器响应了，但状态码不在 2xx 范围内
                      console.log('错误状态:', error.response.status);
            console.log('错误数据:', error.response.data);
            console.log('错误头信息:', error.response.headers);
          this.$message.error(`获取任务列表失败: ${error.response.data?.msg || error.message || '未知错误'}`);
        } else if (error.request) {
          // 请求已经发出，但没有收到响应
                      console.log('错误请求:', error.request);
          this.$message.error('服务器未响应，请检查网络连接');
        } else {
          // 设置请求时发生的错误
                      console.log('错误消息:', error.message);
          this.$message.error('请求错误: ' + (error.message || ''));
        }

        this.taskList = [];
        this.allTaskList = [];
        this.taskTotal = 0;
      } finally {
        this.taskListLoading = false;
      }
    },

    // 计算本地分页数据
    updateLocalPagination() {
      if (!this.allTaskList.length) {
        this.taskList = [];
        this.taskTotal = 0;
        return;
      }
      
      const { pageNum, pageSize } = this.taskQueryParams;
      const startIndex = (pageNum - 1) * pageSize;
      const endIndex = pageNum * pageSize;
      
      // 从全部数据中截取当前页数据
      this.taskList = this.allTaskList.slice(startIndex, endIndex);
      this.taskTotal = this.allTaskList.length;
      
      console.log(`本地分页：第${pageNum}页，每页${pageSize}条，总共${this.taskTotal}条，当前显示${this.taskList.length}条`);
    },

    // 任务列表搜索
    handleTaskSearch() {
      if (this.useLocalPagination) {
        // 前端分页模式下，先重置到第一页
        this.taskQueryParams.pageNum = 1;
        // 重新获取数据并应用本地过滤
        this.fetchTaskList();
      } else {
        // 后端分页模式，直接获取数据
        this.fetchTaskList();
      }
    },

    // 重置任务搜索
    resetTaskSearch() {
      this.taskQueryParams = {
        workOrderCode: '',
        workOrderName: '',
        processCode: '',
        taskName: '',
        taskCode: '',
        status: '',
        pageNum: 1,
        pageSize: 10
      };
      // 重新加载数据
      this.handleTaskSearch();
    },
    
    // 监听分页组件事件，在本地处理分页逻辑
    handleTaskPageChange(page) {
      if (this.useLocalPagination) {
        console.log('前端分页：切换到第', page, '页');
        this.taskQueryParams.pageNum = page;
        // 不重新请求数据，仅更新本地分页
        this.updateLocalPagination();
      } else {
        // 使用原有的后端分页逻辑
        this.taskQueryParams.pageNum = page;
        this.fetchTaskList();
      }
    },
    
    // 处理每页条数变化
    handleTaskSizeChange(size) {
      if (this.useLocalPagination) {
        console.log('前端分页：每页显示', size, '条');
        this.taskQueryParams.pageSize = size;
        // 当改变每页条数时，通常回到第一页
        this.taskQueryParams.pageNum = 1;
        // 不重新请求数据，仅更新本地分页
        this.updateLocalPagination();
      } else {
        // 使用原有的后端分页逻辑
        this.taskQueryParams.pageSize = size;
        this.fetchTaskList();
      }
    },

    // 选择任务
    selectTask(row) {
      console.log('【调试】选择任务，原始数据:', row);
      
      // 填充表单数据
      this.form.sourceDocId = row.workOrderTaskId || 0;
      this.form.sourceDocCode = row.taskCode || '';
      this.form.workOrderCode = row.workOrderCode || '';
      this.form.workOrderName = row.workOrderName || '';
      this.form.taskCode = row.taskCode || '';
      this.form.processCode = row.processCode || '';
      
      // 新增：将任务的planQuantity设置到检测数量中
      if (row.planQuantity !== undefined && row.planQuantity !== null) {
        this.form.quantityCheckNum = Number(row.planQuantity);
        console.log('【调试】设置检测数量为计划数量:', this.form.quantityCheckNum);
      }

      // 关闭对话框
      this.taskDialogVisible = false;
      
      // 显示加载中
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在获取产品信息...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 调用API获取产品信息
      const workOrderTaskId = row.workOrderTaskId;
      console.log('【调试】workOrderTaskId:', workOrderTaskId, '类型:', typeof workOrderTaskId);
      
      if (workOrderTaskId) {
        console.log('【调试】开始调用selectQcIpqcProductInfo API');
        selectQcIpqcProductInfo(workOrderTaskId)
          .then(response => {
            console.log('【调试】selectQcIpqcProductInfo API返回结果:', response);
            loadingInstance.close();
            
            // 处理不同格式的响应
            let productInfo = null;
            
            if (response && response.code === 200) {
              // 标准响应格式：{ code: 200, data: {...} }
              productInfo = response.data;
            } else if (response && typeof response === 'object') {
              // 直接返回对象格式
              productInfo = response;
            }
            
            console.log('【调试】解析后的产品信息:', productInfo);
            
            if (productInfo && (productInfo.product_code || productInfo.product_name || productInfo.productCode || productInfo.productName)) {
              // 处理字段名称不匹配的问题（下划线命名法转驼峰命名法）
              const mappedProductInfo = {
                productId: productInfo.product_id || productInfo.productId,
                productCode: productInfo.product_code || productInfo.productCode,
                productName: productInfo.product_name || productInfo.productName,
                productSfn: productInfo.product_sfn || productInfo.productSfn,
                unit: productInfo.unit
              };
              
              console.log('【调试】字段映射后的产品信息:', mappedProductInfo);
              
              // 填充产品信息
              this.form.productId = mappedProductInfo.productId || this.form.productId;
              this.form.productCode = mappedProductInfo.productCode || this.form.productCode;
              this.form.productName = mappedProductInfo.productName || this.form.productName;
              this.form.productSfn = mappedProductInfo.productSfn || this.form.productSfn;
              this.form.unit = mappedProductInfo.unit || this.form.unit;
              
              console.log('【调试】填充后的产品信息:', {
                productId: this.form.productId,
                productCode: this.form.productCode,
                productName: this.form.productName,
                productSfn: this.form.productSfn,
                unit: this.form.unit
              });
              
              this.$message.success('任务选择成功，已获取产品信息');
              
              // 如果有产品ID，优先触发查询检测方案
              if (this.form.productId) {
                console.log('【调试】有产品ID，准备触发findTemplateByProductCode方法，产品ID:', this.form.productId);
                // 延迟执行，确保表单数据已更新
                setTimeout(() => {
                  console.log('【调试】开始执行findTemplateByProductCode方法，产品ID:', this.form.productId);
                  this.findTemplateByProductCode();
                }, 100);
              } else {
                console.log('【调试】没有产品ID，不触发查询检测方案');
              }
            } else {
              console.warn('【调试】API返回成功但没有有效的产品信息数据');
              this.$message.warning('未获取到产品信息，请手动填写');
            }
          })
          .catch(error => {
            console.error('【调试】selectQcIpqcProductInfo API调用失败:', error);
            loadingInstance.close();
            this.$message.error('获取产品信息失败: ' + (error.message || '未知错误'));
          });
      } else {
        console.warn('【调试】没有workOrderTaskId，不调用API');
        loadingInstance.close();
        this.$message.success('任务选择成功');
      }
    },

    // 获取任务状态显示文本
    getTaskStatusText(status) {
      const statusMap = {
        '0': '未开始',
        '1': '已派工',
        '2': '进行中',
        '3': '已完成',
        '4': '已暂停'
      };
      return statusMap[status] || '未知';
    },

    // 获取任务状态显示类型
    getTaskStatusType(status) {
      const typeMap = {
        '0': 'info',     // 未开始 - 蓝色
        '1': 'warning',  // 已派工 - 黄色
        '2': 'primary',  // 进行中 - 主色
        '3': 'success',  // 已完成 - 绿色
        '4': 'danger'    // 已暂停 - 红色
      };
      return typeMap[status] || '';
    },

    // 打开用户选择对话框
    openUserDialog() {
      this.userDialogVisible = true;
    },
    // 处理用户选择确认
    handleUserConfirm(selection) {
      if (selection && selection.length > 0) {
        // 修改：将用户名称存入inspectorId字段，不再存用户ID
        this.form.inspectorId = selection[0].nickName || selection[0].userName;
        // 保持inspectorName字段不变，仍然存储用户名称
        this.form.inspectorName = selection[0].nickName || selection[0].userName;
        
        console.log('选择检测人员:', selection[0]);
        console.log('修改后的检测人员信息:', {
          inspectorId字段存储: this.form.inspectorId,
          inspectorName字段存储: this.form.inspectorName
        });
      }
      this.userDialogVisible = false;
    },

    // 修改产品编码输入处理
    handleProductCodeInput() {
      // 清除可能的表单校验错误
      if (this.$refs.form) {
        this.$refs.form.clearValidate(['productCode']);
      }
    },

    // 根据产品信息查询对应的质检方案ID
    findTemplateByProductCode() {
      // 修改为使用产品ID而不是产品编码
      const productId = this.form.productId;
      if (!productId) {
        console.warn('【查询检测方案】产品ID为空，无法查询');
        return;
      }
      
      console.log('【查询检测方案】开始通过产品ID查询，产品ID:', productId);
      
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在查询对应的检测方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 调用API查询检测方案，传入产品ID
      selectQcTemplateProductProductCode(productId)
        .then(response => {
          loadingInstance.close();
          
          console.log('【查询检测方案】API返回结果:', response);
          
          // 处理不同格式的返回值
          let templateData = null;
          
          if (response && typeof response === 'object') {
            // 如果返回的是完整对象，保留所有信息
            templateData = response;
          } else if (response && (typeof response === 'number' || typeof response === 'string')) {
            // 直接返回ID值
            templateData = { 
              template_id: response,
              template_code: null,
              template_name: null 
            };
          }
          
          if (templateData) {
            console.log('【通过产品ID查询】获取到的检测方案数据:', templateData);
            
            // 设置方案ID和相关信息
            let templateId, templateCode, templateName;
            
            if (typeof templateData === 'object') {
              // 提取基本信息
              templateId = templateData.template_id || templateData.templateId;
              templateCode = templateData.template_code || templateData.templateCode || '';
              templateName = templateData.template_name || templateData.templateName || '';
              
              // 提取规定检测数据
              if (templateData.quantity_check_num !== undefined) {
                this.form.minCheckNum = templateData.quantity_check_num;
              }
              if (templateData.quantity_unqualified_num !== undefined) {
                this.form.maxUnqualifiedNum = templateData.quantity_unqualified_num;
              }
              
              // 获取接收数量，如果有
              if (templateData.receive_quantity !== undefined) {
                this.form.receiveQuantity = templateData.receive_quantity;
              } else if (this.form.receiveQuantity === 0) {
                // 如果没有设置接收数量，根据实际需求设置一个默认值或查询其他接口获取
                // 这里可以添加逻辑来获取接收数量
              }
            } else {
              templateId = templateData;
            }
            
            // 确保模板ID为数字
            const numTemplateId = parseInt(templateId, 10);
            if (isNaN(numTemplateId)) {
              console.warn('获取到的检测方案ID格式不正确:', templateId);
              this.$message.error('检测方案ID格式不正确');
              return;
            }
            
            // 设置模板ID和名称
            this.form.inspectPlanId = numTemplateId;
            if (templateCode) this.form.inspectPlanCode = templateCode;
            if (templateName) this.form.inspectPlanName = templateName;
            
            // 提示用户已应用检测方案
            this.$notify({
              title: '检测方案已应用',
              message: `已应用检测方案: ${this.form.inspectPlanName || numTemplateId}，最低检测数=${this.form.minCheckNum}，最大不合格数=${this.form.maxUnqualifiedNum}`,
              type: 'success',
              duration: 5000
            });
            
            // 确保合格数量计算正确
            this.$nextTick(() => {
              this.updateQualifiedQuantity();
            });
            
            // 清除模板ID字段的验证提示
            if (this.$refs.form) {
              this.$refs.form.clearValidate(['inspectPlanId']);
            }
          } else {
            console.log('【通过产品ID查询】未找到检测方案ID');
            this.$message.warning('未找到对应的检测方案，请手动选择');
          }
        })
        .catch(error => {
          loadingInstance.close();
          console.error('【错误】通过产品ID查询检测方案异常:', error);
          this.$message.error('查询检测方案失败: ' + (error.message || '未知错误'));
        });
    },
    
    // 根据物料编码查询对应的质检方案ID
    findTemplateByMaterialCode(materialCode) {
      if (!materialCode) {
        console.warn('【查询检测方案】物料编码为空，无法查询');
        return;
      }
      
      console.log('【查询检测方案】开始查询，物料编码:', materialCode);
      
      const loadingInstance = this.$loading({
        lock: true,
        text: '正在查询对应的检测方案...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      // 调用API查询检测方案
      selectQcTemplateProductMaterialCode(materialCode)
        .then(response => {
          loadingInstance.close();
          
          console.log('【查询检测方案】API返回结果:', response);
          
          // 处理不同格式的返回值
          let templateId = null;
          
          if (response && typeof response === 'object' && response.code === 200) {
            // 标准响应格式
            templateId = response.data;
          } else if (response && (typeof response === 'number' || typeof response === 'string')) {
            // 直接返回ID值
            templateId = response;
          }
          
          if (templateId) {
            console.log('【通过物料编码查询】获取到的检测方案ID:', templateId);
            this.setTemplateInfo(templateId);
          } else {
            console.warn('【通过物料编码查询】未找到检测方案，请手动选择');
            this.$message.info('未找到对应的检测方案，请手动选择');
          }
        })
        .catch(error => {
          loadingInstance.close();
          console.error('【错误】通过物料编码查询检测方案异常:', error);
          this.$message.error('查询检测方案失败: ' + (error.message || '未知错误'));
        });
    },
    
    // 设置模板信息到表单
    setTemplateInfo(templateId) {
      if (!templateId) return;
      
      console.log('【开始设置模板信息】检测方案ID：', templateId);
      
      // 先设置ID，确保即使后续API调用失败，ID也已设置到表单中
      this.form.inspectPlanId = parseInt(templateId, 10);
      
      // 清除模板ID字段的验证提示
      if (this.$refs.form) {
        this.$refs.form.clearValidate(['inspectPlanId']);
      }
      
      this.$message.success(`已自动设置检测方案ID: ${templateId}`);
    },
    
    // 处理检测数量变化
    handleCheckNumChange(value) {
      // 确保检测数量为非负整数
      const checkNum = Math.max(0, parseInt(value) || 0);
      this.form.quantityCheckNum = checkNum;
      
      // 检查是否超过接收数量
      if (this.form.receiveQuantity > 0 && checkNum > this.form.receiveQuantity) {
        this.$message.warning(`检测数量(${checkNum})不能超过接收数量(${this.form.receiveQuantity})`);
      }
      
      // 自动调整不合格数，确保不超过检测数量
      if (this.form.quantityUnqualifiedNum > checkNum) {
        this.form.quantityUnqualifiedNum = checkNum;
        this.$message.info('已自动调整不合格数，使其不超过检测数量');
      }
      
      // 计算合格数量
      this.updateQualifiedQuantity();
      
      // 重新计算缺陷率
      this.calculateDefectRates();
    },
    
    // 处理不合格数变化
    handleUnqualifiedNumChange(value) {
      // 确保不合格数为非负整数且不超过检测数量
      const checkNum = this.form.quantityCheckNum || 0;
      const unqualifiedNum = Math.min(checkNum, Math.max(0, parseInt(value) || 0));
      this.form.quantityUnqualifiedNum = unqualifiedNum;
      
      // 计算合格数量
      this.updateQualifiedQuantity();
      
      // 检查是否超过最大不合格数
      if (this.form.maxUnqualifiedNum > 0 && unqualifiedNum > this.form.maxUnqualifiedNum) {
        // 自动设置为不合格
        if (this.form.checkResult !== '2') {
          this.form.checkResult = '2'; // 设置为不合格
          this.$message.warning(`不合格数(${unqualifiedNum})已超过最大允许值(${this.form.maxUnqualifiedNum})，已自动设为不合格`);
        }
      } else if (unqualifiedNum === 0 && checkNum > 0) {
        // 如果没有不合格品且检测数量大于0，自动设为合格
        this.form.checkResult = '1';
      }
      
      // 重新计算缺陷率
      this.calculateDefectRates();
    },
    
    // 更新合格数量
    updateQualifiedQuantity() {
      const checkNum = this.form.quantityCheckNum || 0;
      const unqualifiedNum = this.form.quantityUnqualifiedNum || 0;
      this.form.quantityQualifiedNum = Math.max(0, checkNum - unqualifiedNum);
    },
    
    // 计算缺陷率
    calculateDefectRates() {
      const checkNum = this.form.quantityCheckNum || 0;
      if (checkNum <= 0) {
        this.form.crRate = 0;
        this.form.majRate = 0;
        this.form.minRate = 0;
        return;
      }
      
      const crNum = this.form.crQuantityNum || 0;
      const majNum = this.form.majQuantityNum || 0;
      const minNum = this.form.minQuantityNum || 0;
      
      // 计算百分比，保留2位小数
      this.form.crRate = parseFloat(((crNum / checkNum) * 100).toFixed(2));
      this.form.majRate = parseFloat(((majNum / checkNum) * 100).toFixed(2));
      this.form.minRate = parseFloat(((minNum / checkNum) * 100).toFixed(2));
      
      console.log('缺陷率计算结果:', {
        检测数量: checkNum,
        致命缺陷数量: crNum,
        严重缺陷数量: majNum,
        轻微缺陷数量: minNum,
        致命缺陷率: this.form.crRate,
        严重缺陷率: this.form.majRate,
        轻微缺陷率: this.form.minRate
      });
    },
    handlePagination({ page, limit }) {
      if (this.useLocalPagination) {
        console.log('分页组件触发: 页码=', page, '每页条数=', limit);
        this.taskQueryParams.pageNum = page;
        this.taskQueryParams.pageSize = limit;
        // 本地处理分页
        this.updateLocalPagination();
      } else {
        // 后端分页
        this.taskQueryParams.pageNum = page;
        this.taskQueryParams.pageSize = limit;
        this.fetchTaskList();
      }
    },
         // 生成检验单编号
    generatePlanCode() {
      getAutoNumbers(8).then(response => {
        if (response.code === 200) {
          this.form.ipqcCode = response.msg;
          // 使用nextTick确保DOM更新后触发校验
          this.$nextTick(() => {
            if (this.$refs.form) {
              this.$refs.form.validateField('ipqcCode');
            }
          });
        } else {
          this.$message.error('获取检验单编号失败');
        }
      }).catch(() => {
        this.$message.error('获取检验单编号失败');
      });
    },
    
          // 处理系统编号开关变化
    handleSystemCodeChange(val) {
      if (val) {
        // 如果开启系统编号，则生成编号
        this.generatePlanCode();
      } else {
        // 如果关闭系统编号，则清空编号
        this.form.ipqcCode = '';
      }
      
      // 使用nextTick确保DOM更新后触发校验
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.validateField('ipqcCode');
        }
      });
        }
  }
};
</script>

<style scoped>
.ipqc-form {
  padding: 10px;
  height: 700px; /* 设置固定高度 */
  width: 100%;
  position: relative;
  background-color: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 表单卡片样式 */
.form-card {
  margin-bottom: 15px;
  border-radius: 4px;
}

/* 卡片标题样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 15px;
  font-weight: 500;
  color: #303133;
}

/* 表单容器 */
.form-container {
  padding: 8px 5px;
}

/* 表单项样式 */
.form-item {
  margin-bottom: 12px;
}

/* 顶部导航标签 */
.form-tabs {
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 5px 15px 0;
  flex-shrink: 0; /* 不压缩 */
}

.form-tabs .el-tabs__header {
  margin-bottom: 0;
  height: 40px;
}

.form-content-area {
  background-color: transparent;
  flex: 1; /* 占用剩余空间 */
  overflow-y: auto; /* 内容过多时显示滚动条 */
}

/* Select禁用状态的特殊样式 */
::v-deep .el-select.is-disabled .el-input__inner {
  background-color: #f5f7fa !important;
  border-color: #e4e7ed !important;
  color: #606266 !important;
  border-style: dashed !important;
  cursor: not-allowed !important;
}

.form-footer {
  height: 50px;
  text-align: center;
  background: #fff;
  padding: 8px 0;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 10px;
  flex-shrink: 0; /* 不压缩 */
  border-radius: 4px;
}

/* 确保输入框宽度一致 */
.el-input {
  width: 100%;
}

/* 调整表单项之间的间距，避免太大的空白区域 */
.el-form-item {
  margin-bottom: 15px;
}

/* 调整textarea高度 */
.el-textarea {
  width: 100%;
}

/* 确保内容不被底部按钮遮挡 */
.el-form {
  padding-bottom: 5px;
}

/* 整体字体大小略微缩小，增加内容密度 */
.ipqc-form {
  font-size: 0.95em;
}

/* 调整行间距以适应更多内容 */
.el-row {
  margin-bottom: 5px;
}

/* 数字输入框样式调整 */
.el-input-number.el-input-number--medium {
  width: 100%;
}

/* 自动生成按钮样式 */
.auto-code-btn,
.select-plan-btn,
.select-btn {
  margin-left: 10px;
}

/* 禁用输入框样式 */
.disabled-input {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  border: 1px dashed #d9d9d9 !important;
  cursor: not-allowed !important;
}

.disabled-input input,
.disabled-input .el-input__inner,
.disabled-input .el-select .el-input.is-disabled .el-input__inner {
  background-color: #f5f7fa !important;
  color: #606266 !important;
  cursor: not-allowed !important;
  -webkit-text-fill-color: #606266 !important;
}

/* 输入框和按钮的容器样式 */
.code-input-wrapper {
  display: flex;
  align-items: center;
}

/* 必填项红色星号样式 */
::v-deep .el-form-item.is-required .el-form-item__label:before {
  color: #f56c6c;
}

/* 标签样式调整，匹配图片中的样式 */
::v-deep .el-form-item__label {
  color: #606266;
  font-size: 14px;
  line-height: 40px;
  text-align: right;
  vertical-align: middle;
  float: left;
  padding: 0 12px 0 0;
  box-sizing: border-box;
}

/* 缺陷详情部分样式 */
.defect-details-section {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px dashed #e0e0e0;
}

.section-divider {
  font-size: 14px;
  font-weight: 500;
  color: #409EFF;
  margin-bottom: 15px;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
  line-height: 16px;
}

/* 产品选择对话框样式 */
.product-dialog-container,
.task-dialog-container {
  padding: 10px;
}

.search-form {
  margin-bottom: 15px;
}

/* 表格鼠标悬停效果 */
::v-deep .el-table tbody tr:hover>td {
  background-color: #f5f7fa;
  cursor: pointer;
}

/* 检测项目容器 */
.test-items-container {
  padding: 10px 0;
}

/* 表头右侧操作按钮 */
.header-right {
  float: right;
}

/* 空数据提示 */
.empty-data {
  padding: 30px 0;
  text-align: center;
}

.empty-tips {
  font-size: 14px;
  color: #909399;
  margin-top: 10px;
}

/* 表格内部样式 */
::v-deep .el-table {
  margin-bottom: 20px;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.plan-id-info {
  margin-top: 8px;
  margin-left: 5px;
  display: flex;
  align-items: center;
}

.plan-id-info .el-tag {
  font-weight: 500;
  margin-right: 10px;
}

/* 响应式样式调整 */
@media screen and (max-width: 1400px) {
  .ipqc-form {
    padding: 5px;
  }

  .el-row {
    margin-left: -5px !important;
    margin-right: -5px !important;
  }

  .el-col {
    padding-left: 5px !important;
    padding-right: 5px !important;
  }
}

/* 修复对话框样式，防止溢出 */
::v-deep .el-dialog {
  max-width: 95%;
  margin: 0 auto;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
  display: flex;
  align-items: center;
}

.form-tip .el-icon-info,
.form-tip .el-icon-warning {
  margin-right: 5px;
}

.form-tip.warning {
  color: #E6A23C;
}

.form-tip.warning .el-icon-warning {
  color: #E6A23C;
}

.form-tip strong {
  color: #F56C6C;
  font-weight: bold;
}
</style>
